﻿// ----------------------------------------------------------------------------------------
// Author:                    Magaly Vargas y Joaquín López
// Company:                   ALBALIA INTERACTIVA S.L.
// Assembly version:          1.0.0.0
// Date:                      22/02/2010
// Time:                      12:00
// Solution Name:             OffInvoiceWordTemplate
// Solution Filename:         OffInvoiceWordTemplate
// Solution FullFilename:     C:\Desarrollo\OffInvoiceWordTemplate
// Project Name:              OffInvoiceWordTemplate
// Project Filename:          OffInvoiceWordTemplate.csproj
// Project FullFilename:      C:\Desarrollo\OffInvoiceWordTemplate\OffInvoiceWordTemplate.csproj
// Project Item Name:         ThisDocument.cs
// Project Item Filename:     ThisDocument.cs
// Project Item FullFilename: C:\Desarrollo\OffInvoiceWordTemplate\ThisDocument.cs
// Project Item Kind:         Código
// Purpose:                   
//Copyright © 2009 - 2010 Albalia Interactiva S.L. Reservados todos los derechos.
// ----------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using Microsoft.Office.Tools.Word;
using Microsoft.VisualStudio.Tools.Applications.Runtime;
using Office = Microsoft.Office.Core;
using Word = Microsoft.Office.Interop.Word;
using System.Globalization;
using System.Xml;
using System.Xml.Serialization;
using System.Reflection;
using System.IO;
using Microsoft.Office.Interop.Word;



namespace OffInvoiceWordTemplate
{
    public partial class ThisDocument
    {

        #region Fields

        CultureInfo cInfo;
        String language;
        string languajePath;
        string messagePath;


        /// <summary>
        /// array de caracteres a eliminar de los valores tomados directamente de las celdas de una table
        /// </summary>
        char[] x = { '\r', '\a', '\n' };

        ///// <summary>
        ///// base sobre la que se calculan los descuentos generales
        ///// </summary>
        //double GeneralDiscountBase;

        ///// <summary>
        ///// totalGrossAmount = el monto total bruto antes de los descuentos generales
        ///// </summary>

        //double totalGrossAmount;


        ///// <summary>
        ///// totalGeneralDiscount = total de los descuentos generales
        ///// </summary>
        //double totalGeneralDiscount;

        ///// <summary>
        /////  TotalTaxesOutputs = total de impuestos repercutidos
        ///// </summary>
        //double TotalTaxesOutputs;


        ///// <summary>
        ///// TotalTaxesWithHeld = total de impuestos retenidos
        ///// </summary>
        //double TotalTaxesWithHeld;

        /// <summary>
        /// almacena el indice de la tabla principal, donde se encuantran los datos de las partes, emisor y cliente
        /// </summary>
        int t1;

        /// <summary>
        /// almacena el índice de la tabla de detalles
        /// </summary>
        int t2;

        /// <summary>
        /// almacena el índice de la tabla de descuentos
        /// </summary>
        int t3;

        /// <summary>
        /// almacena el índice de la tabla de observaciones
        /// </summary>
        int t4;

        /// <summary>
        /// almacena el índice de la tabla de totales
        /// </summary>
        int t5;

        /// <summary>
        /// almacena el indice de la tabla de informacion de tercero
        /// </summary>
        int t6;

        /// <summary>
        /// almacena la cultura del sistema, para control de conversion de datos, tomando en cuenta separadores de decimales y de millares
        /// </summary>
        CultureInfo culture;

        /// <summary>
        /// define los separadors de decimales y millares
        /// </summary>
        NumberFormatInfo num;

        XmlDocument docLanguage;

        Calculos calculos;

        FieldFormats ff;

        #endregion

        #region EventHandlerMethods

        /// <summary>
        /// se ejcuta al abrirse un documento de basado en la plantilla
        /// Carga los combobox de país, de emisor de la factura y de moneda
        /// inicializa los totales. y protege la tabla principal 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ThisDocument_Startup(object sender, System.EventArgs e)
        {
            //CultureInfo cInfo = new CultureInfo(this.Application.LanguageSettings.get_LanguageID(Microsoft.Office.Core.MsoAppLanguageID.msoLanguageIDUI));
            culture = new CultureInfo(this.Application.LanguageSettings.get_LanguageID(Microsoft.Office.Core.MsoAppLanguageID.msoLanguageIDUI));
            num = culture.NumberFormat;

            //String language = cInfo.Name;
            String language = culture.Name;

            languajePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\Microsoft OffInvoice\Languages\" + language + ".xml";
            messagePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\Microsoft OffInvoice\Messages\" + language + ".xml";

            this.Application.DocumentBeforeSave += new Microsoft.Office.Interop.Word.ApplicationEvents4_DocumentBeforeSaveEventHandler(Application_DocumentBeforeSave);

            //culture = CultureInfo.InstalledUICulture;
            //num = culture.NumberFormat;

            ff = new FieldFormats(culture, num, language);
            calculos = new Calculos(ff);
            calculos.taxes.AmmountPrefix = string.Concat(Loader.LoadLabel(messagePath, "Infotaxamount"));
            calculos.taxes.BaseImponiblePrefix = string.Concat(Loader.LoadLabel(messagePath, "InfoTaxablebaxe"));

            try
            {
                enumerateTables();

                try
                {
                    this.cbxCountryEM.DropDownListEntries.Clear();
                    this.cbxCountryBP.DropDownListEntries.Clear();
                    this.cbxCurrency.DropDownListEntries.Clear();


                    string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\Microsoft OffInvoice\InformationFiles\" + language + @"\Countries.txt";

                    string[] data = { "Afganistán", "AFG", "Albania", "ALB", "Alemania", "DEU", "Andorra", "AND", "Angola", "AGO", "Anguilla", "AIA", "Antigua y Barbuda", "ATG", "Antillas Holandesas", "ANT", "Arabia Saudí", "SAU", "Argelia", "DZA", "Argentina", "ARG", "Armenia", "ARM", "Aruba", "ABW", "ARY Macedonia", "MKD", "Australia", "AUS", "Austria", "AUT", "Azerbaiyán", "AZE", "Bahamas", "BHS", "Bahréin", "BHR", "Bangladesh", "BGD", "Barbados", "BRB", "Bélgica", "BEL", "Belice", "BLZ", "Benin", "BEN", "Bermudas", "BMU", "Bhután", "BTN", "Bielorrusia", "BLR", "Bolivia", "BOL", "Bosnia y Herzegovina", "BIH", "Botsuana", "BWA", "Brasil", "BRA", "Brunéi", "BRN", "Bulgaria", "BGR", "Burkina Faso", "BFA", "Burundi", "BDI", "Cabo Verde", "CPV", "Camboya", "KHM", "Camerún", "CMR", "Canadá", "CAN", "Chad", "TCD", "Chile", "CHL", "China", "CHN", "Chipre", "CYP", "Ciudad del Vaticano", "VAT", "Colombia", "COL", "Comoras", "COM", "Congo", "COG", "Corea del Norte", "PRK", "Corea del Sur", "KOR", "Costa de Marfil", "CIV", "Costa Rica", "CRI", "Croacia", "HRV", "Cuba", "CUB", "Dinamarca", "DNK", "Dominica", "DMA", "Ecuador", "ECU", "Egipto", "EGY", "El Salvador", "SLV", "Emiratos Árabes Unidos", "ARE", "Eritrea", "ERI", "Eslovaquia", "SVK", "Eslovenia", "SVN", "España", "ESP", "Estados Unidos", "USA", "Estonia", "EST", "Etiopía", "ETH", "Filipinas", "PHL", "Finlandia", "FIN", "Fiyi", "FJI", "Francia", "FRA", "Gabón", "GAB", "Gambia", "GMB", "Georgia", "GEO", "Ghana", "GHA", "Gibraltar", "GIB", "Granada", "GRD", "Grecia", "GRC", "Groenlandia", "GRL", "Guadalupe", "GLP", "Guam", "GUM", "Guatemala", "GTM", "Guayana Francesa", "GUF", "Guernsey", "GGY", "Guinea", "GIN", "Guinea Ecuatorial", "GNQ", "Guinea-Bissau", "GNB", "Guyana", "GUY", "Haití", "HTI", "Honduras", "HND", "Hong Kong", "HKG", "Hungría", "HUN", "India", "IND", "Indonesia", "IDN", "Irán", "IRN", "Iraq", "IRQ", "Irlanda", "IRL", "Isla de Man", "IMN", "Isla Norfolk", "NFK", "Islandia", "ISL", "Islas Caimán", "CYM", "Islas Cook", "COK", "Islas Feroe", "FRO", "Islas Malvinas", "FLK", "Islas Marianas del Norte", "MNP", "Islas Marshall", "MHL", "Islas Pitcairn", "PCN", "Islas Salomón", "SLB", "Islas Turcas y Caicos", "TCA", "Islas Vírgenes Británicas", "VGB", "Islas Vírgenes de los Estados Unidos", "VIR", "Israel", "ISR", "Italia", "ITA", "Jamaica", "JAM", "Japón", "JPN", "Jersey", "JEY", "Jordania", "JOR", "Kazajstán", "KAZ", "Kenia", "KEN", "Kirguistán", "KGZ", "Kiribati", "KIR", "Kuwait", "KWT", "Laos", "LAO", "Lesotho", "LSO", "Letonia", "LVA", "Líbano", "LBN", "Liberia", "LBR", "Libia", "LBY", "Liechtenstein", "LIE", "Lituania", "LTU", "Luxemburgo", "LUX", "Macao", "MAC", "Madagascar", "MDG", "Malasia", "MYS", "Malawi", "MWI", "Maldivas", "MDV", "Malí", "MLI", "Malta", "MLT", "Marruecos", "MAR", "Martinica", "MTQ", "Mauricio", "MUS", "Mauritania", "MRT", "Mayotte", "MYT", "México", "MEX", "Micronesia", "FSM", "Moldavia", "MDA", "Mónaco", "MCO", "Mongolia", "MNG", "Montenegro", "MNE", "Montserrat", "MSR", "Mozambique", "MOZ", "Myanmar", "MMR", "Namibia", "NAM", "Nauru", "NRU", "Nepal", "NPL", "Nicaragua", "NIC", "Níger", "NER", "Nigeria", "NGA", "Niue", "NIU", "Noruega", "NOR", "Nueva Caledonia", "NCL", "Nueva Zelanda", "NZL", "Omán", "OMN", "Países Bajos", "NLD", "Pakistán", "PAK", "Palau", "PLW", "Palestina", "PSE", "Panamá", "PAN", "Papúa Nueva Guinea", "PNG", "Paraguay", "PRY", "Perú", "PER", "Polinesia Francesa", "PYF", "Polonia", "POL", "Portugal", "PRT", "Puerto Rico", "PRI", "Qatar", "QAT", "Reino Unido", "GBR", "República Centroafricana", "CAF", "República Checa", "CZE", "República Democrática del Congo", "COD", "República Dominicana", "DOM", "Reunión", "REU", "Ruanda", "RWA", "Rumania", "ROU", "Rusia", "RUS", "Sahara Occidental", "ESH", "Samoa", "WSM", "Samoa Americana", "ASM", "San Cristóbal y Nevis", "KNA", "San Marino", "SMR", "San Pedro y Miquelón", "SPM", "San Vicente y las Granadinas", "VCT", "Santa Helena", "SHN", "Santa Lucía", "LCA", "Santo Tomé y Príncipe", "STP", "Senegal", "SEN", "Serbia", "SRB", "Seychelles", "SYC", "Sierra Leona", "SLE", "Singapur", "SGP", "Siria", "SYR", "Somalia", "SOM", "Sri Lanka", "LKA", "Suazilandia", "SWZ", "Sudáfrica", "ZAF", "Sudán", "SDN", "Suecia", "SWE", "Suiza", "CHE", "Surinam", "SUR", "Svalbard y Jan Mayen", "SJM", "Tailandia", "THA", "Taiwán", "TWN", "Tanzania", "TZA", "Tayikistán", "TJK", "Timor Oriental", "TLS", "Togo", "TGO", "Tokelau", "TKL", "Tonga", "TON", "Trinidad y Tobago", "TTO", "Túnez", "TUN", "Turkmenistán", "TKM", "Turquía", "TUR", "Tuvalu", "TUV", "Ucrania", "UKR", "Uganda", "UGA", "Uruguay", "URY", "Uzbekistán", "UZB", "Vanuatu", "VUT", "Venezuela", "VEN", "Vietnam", "VNM", "Wallis y Futuna", "WLF", "Yemen", "YEM", "Yibuti", "DJI", "Zaire", "ZAR", "Zambia", "ZMB", "Zimbabue", "ZWE" };

                    char[] sep = { '\t' };

                    string datos = ReadFile(path);

                    if (!string.IsNullOrEmpty(datos))
                    {
                        data = datos.Replace("\r\n", "\t").Trim().Split('\t');
                    }


                    this.lbnDetails.Text = Loader.LoadLabel(languajePath, lbnDetails.Name);
                    this.lbnDiscounts.Text = Loader.LoadLabel(languajePath, lbnDetails.Name);

                    LoadComboBox(this.cbxCountryEM, data);
                    LoadComboBox(this.cbxCountryBP, data);

                    string pathCorrectiveReason = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\Microsoft OffInvoice\InformationFiles\" + language;

                    loadCorrectiveReason(pathCorrectiveReason + @"\correctionReason.txt", "CORR_ReasonDescription");
                    loadCorrectiveReason(pathCorrectiveReason + @"\correctionMethod.txt", "CORR_CorrectionMethodDescription");
                    try
                    {
                        this.cbxCountryTH.DropDownListEntries.Clear();
                        LoadComboBox(this.cbxCountryTH, data);
                    }
                    catch (Exception) { }


                }
                catch (Exception) { }

                this.cbxCurrency.LockContents = false;
                foreach (int item in Enum.GetValues(typeof(CurrencyCodeType)))
                {
                    this.cbxCurrency.DropDownListEntries.Add(Enum.GetName(typeof(CurrencyCodeType), item), Enum.GetName(typeof(CurrencyCodeType), item), item);

                }

                txtExchangeRate.Text = ff.txtExchangeRate("1");

                CultureInfo cult = new CultureInfo(Globals.ThisDocument.Application.LanguageSettings.get_LanguageID(Microsoft.Office.Core.MsoAppLanguageID.msoLanguageIDUI));

                dtpIssueDate.DateDisplayFormat = cult.DateTimeFormat.ShortDatePattern.ToString();
                dtpDevengo.DateDisplayFormat = cult.DateTimeFormat.ShortDatePattern.ToString();
                dtpIssueDate.Text = DateTime.Today.ToString(cult);
                dtpDevengo.Text = DateTime.Today.ToString(cult);

            }

            catch (Exception) { }

            try
            {
                cargarN_Fila(this.cbxnDetails, t2);
                cargarN_Fila(this.cbxnDiscount, t3);
            }
            catch (Exception) { }

            try
            {
                this.Tables[1].Range.Select();
                this.Controls.AddGroupContentControl("group");
                this.dtpIssueDate.Range.Select();

            }
            catch (Exception) { }

            try
            {
                if (t6 == 0)
                {
                    this.cbxIssuerType.DropDownListEntries.Clear();
                    this.cbxIssuerType.DropDownListEntries.Add(Loader.LoadLabel(languajePath, "itemReceptor"), "RE", 0);
                    this.cbxIssuerType.DropDownListEntries.Add(Loader.LoadLabel(languajePath, "itemEmisor"), "EM", 1);

                }
            }
            catch (Exception) { }

        }

        /// <summary>
        /// antes de guardarse un documento basado en esta plantilla, llama al método protectIssuedDocument(), que bloquea el documento, si ç
        /// el estado es recibido o emitido
        /// </summary>
        /// <param name="Doc"></param>
        /// <param name="SaveAsUI"></param>
        /// <param name="Cancel"></param>
        private void Application_DocumentBeforeSave(Microsoft.Office.Interop.Word.Document Doc, ref bool SaveAsUI, ref bool Cancel)
        {
            protectIssuedDocument();
        }

        /// <summary>
        /// Controla el evento de salida dl documento
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ThisDocument_Shutdown(object sender, System.EventArgs e)
        {
        }

        /// <summary>
        /// evento del botón agregar detalles.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddDetails_Click(object sender, EventArgs e)
        {
            try
            {
                enumerateTables();
                calculos.resetTotals();
                computeDetails(true);
                computeDiscount(false);
                cargarN_Fila(this.cbxnDetails, t2);
            }
            catch (Exception) { }

        }

        /// <summary>
        /// Evento del botón modificar detalles
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnModifyDetails_Click(object sender, EventArgs e)
        {
            try
            {
                enumerateTables();
                calculos.resetTotals();
                computeDetails(false);
                computeDiscount(false);
                cargarN_Fila(this.cbxnDetails, t2);
            }
            catch (Exception) { }
        }

        /// <summary>
        /// Evento del botón eliminar detalles
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDeleteDetails_Click(object sender, EventArgs e)
        {

            try
            {
                enumerateTables();
                calculos.resetTotals();


                if (this.cbxnDetails.SelectedValue == null || string.IsNullOrEmpty(this.cbxnDetails.SelectedValue.ToString()))
                {
                    throw new Exception("lbnDetails");
                }

                string selectedRow = this.cbxnDetails.SelectedValue.ToString();
                int deletedRow = int.Parse(selectedRow);
                if (this.Tables[t2].Rows.Count > 3)
                {
                    this.Tables[t2].Rows[deletedRow].Delete();
                    ResetTotals();
                    computeDetails(false);
                    cargarN_Fila(this.cbxnDetails, t2);
                    if (this.Tables[t3].Rows.Count > 3)
                    {
                        computeDiscount(false);
                    }
                }
                else
                {
                    ResetTotals();
                }

                if (this.Tables[t2].Rows.Count == 3)
                {
                    for (int j = this.Tables[t3].Rows.Count - 1; j >= 3; j--)
                    {
                        this.Tables[t3].Rows[j].Delete();
                        cargarN_Fila(cbxnDiscount, t3);
                    }
                }
                updateResultsTable();

                txtDiscountReason.Text = "";
                txtDiscountRate.Text = "";

            }
            catch (Exception ex)
            {
                cargarN_Fila(cbxnDetails, t2);
                MessageBox.Show(Loader.LoadLabel(languajePath, ex.Message), "Detalles", MessageBoxButtons.OK, MessageBoxIcon.Stop, MessageBoxDefaultButton.Button1);
            }

        }

        /// <summary>
        /// evento del botón agregar descuentos
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddDiscount_Click(object sender, EventArgs e)
        {
            enumerateTables();
            if (this.Tables[t2].Rows.Count > 3)
            {
                computeDiscount(true);
                cargarN_Fila(this.cbxnDiscount, t3);
            }
        }

        /// <summary>
        /// Evento del botón modificar descuentos
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnModifyDiscount_Click(object sender, EventArgs e)
        {

            enumerateTables();
            if (this.Tables[t2].Rows.Count > 3)
            {
                computeDiscount(false);
                cargarN_Fila(this.cbxnDiscount, t3);
            }
        }

        /// <summary>
        /// evento del botón eliminar descuentos
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDeleteDiscount_Click(object sender, EventArgs e)
        {
            try
            {
                enumerateTables();

                if (this.cbxnDiscount.SelectedValue == null || string.IsNullOrEmpty(this.cbxnDiscount.SelectedValue.ToString()))
                {
                    throw new Exception("lbnDetails");
                }

                string selectedRow = this.cbxnDiscount.SelectedValue.ToString();

                int deletedRow = int.Parse(selectedRow);

                if (this.Tables[t3].Rows.Count > 3)
                {
                    this.Tables[t3].Rows[deletedRow].Delete();
                    computeDiscount(false);
                    cargarN_Fila(this.cbxnDiscount, t3);
                }

                updateResultsTable();
            }
            catch (Exception ex)
            {
                cargarN_Fila(cbxnDiscount, t3);
                MessageBox.Show(Loader.LoadLabel(languajePath, ex.Message), Loader.LoadLabel(messagePath, "captionDiscounts"), MessageBoxButtons.OK, MessageBoxIcon.Stop, MessageBoxDefaultButton.Button1);

            }
        }

        #endregion

        #region private Methods

        private void computeDetails(bool newDetail)
        {

            int rowcount = this.Tables[t2].Rows.Count;

            if (!newDetail)
            {
                rowcount = rowcount - 1;
            }

            object[,] detailrows = new object[rowcount - 2, 7];

            for (int i = 3; i <= rowcount; i++)
            {
                detailrows[i - 3, 0] = this.Tables[t2].Rows[i].Cells[1].Range.Text.Trim(x).Trim();
                detailrows[i - 3, 1] = this.Tables[t2].Rows[i].Cells[2].Range.Text.Trim(x).Trim();
                detailrows[i - 3, 2] = this.Tables[t2].Rows[i].Cells[3].Range.Text.Trim(x).Trim();
                detailrows[i - 3, 3] = this.Tables[t2].Rows[i].Cells[4].Range.Text.Trim(x).Trim();
                detailrows[i - 3, 4] = this.Tables[t2].Rows[i].Cells[5].Range.Text.Trim(x).Trim();
                detailrows[i - 3, 5] = this.Tables[t2].Rows[i].Cells[6].Range.Text.Trim(x).Trim();
                detailrows[i - 3, 6] = this.Tables[t2].Rows[i].Cells[7].Range.Text.Trim(x).Trim();
            }

            object[,] resultdetails = calculos.computeDetails(detailrows);


            if (newDetail)
            {
                object rowBefore = this.Tables[t2].Rows.Last;
                this.Tables[t2].Rows.Add(ref rowBefore);
                rowcount = Tables[t2].Rows.Count;
            }


            for (int i = 0; i < resultdetails.GetLength(0); i++)
            {

                setDetailLineData(true, i + 3, resultdetails[i, 0].ToString(), resultdetails[i, 1].ToString(), (double)resultdetails[i, 2],
                    (double)resultdetails[i, 3], (double)resultdetails[i, 4],
                    (double)resultdetails[i, 5], (double)resultdetails[i, 6],
                    (double)resultdetails[i, 7], (double)resultdetails[i, 8]);
            }

            updateResultsTable();

            txtConcepto.Text = "";
            txtUd.Text = "";
            txtPrice.Text = "";
            txtDiscount.Text = "";
            cbxIVA.Text = "16";
            txtTaxableBase.Text = "";
            txtImporte.Text = "";

        }

        private void computeDiscount(bool newDiscount)
        {


            int rowcount = this.Tables[t3].Rows.Count;

            if (!newDiscount)
            {
                rowcount = rowcount - 1;
            }

            object[,] discountRows = new object[rowcount - 2, 2];


            for (int i = 3; i <= rowcount; i++)
            {
                discountRows[i - 3, 0] = this.Tables[t3].Rows[i].Cells[1].Range.Text.Trim(x).Trim();
                discountRows[i - 3, 1] = this.Tables[t3].Rows[i].Cells[2].Range.Text.Trim(x).Trim();
            }

            object[,] results = calculos.computeDiscount(discountRows);

            if (newDiscount)
            {
                object rowBefore = this.Tables[t3].Rows.Last;
                this.Tables[t3].Rows.Add(ref rowBefore);
                rowcount = Tables[t3].Rows.Count;
            }

            for (int i = 0; i < results.GetLength(0); i++)
            {
                this.Tables[t3].Rows[i + 3].Cells[1].Range.Text = results[i, 0].ToString();
                this.Tables[t3].Rows[i + 3].Cells[2].Range.Text = ff.twoDecimalFormat(results[i, 1].ToString());
                this.Tables[t3].Rows[i + 3].Cells[3].Range.Text = ff.twoDecimalFormat(results[i, 2].ToString());

                updateResultsTable();

                txtDiscountReason.Text = "";
                txtDiscountRate.Text = "";
            }
        }

        private void setTaxesOutputs()
        {


            List<Taxes> taxesList = calculos.taxes.TaxesList;

            try
            {
                if (taxesList != null)
                {
                    foreach (Taxes tax in taxesList)
                    {
                        object rowBefore = this.Tables[t5].Rows.Last.Previous;
                        this.Tables[t5].Rows.Add(ref rowBefore);
                        int index = this.Tables[t5].Rows.Last.Previous.Previous.Index;
                        this.Tables[t5].Rows[index].Cells[2].Range.Text = tax.BaseImponiblePrefix;
                        this.Tables[t5].Rows[index].Cells[3].Range.Text = string.Format(num, "{0:#,0.00}", tax.Taxablebase);
                        rowBefore = this.Tables[t5].Rows.Last.Previous;
                        this.Tables[t5].Rows.Add(ref rowBefore);
                        index = this.Tables[t5].Rows.Last.Previous.Previous.Index;
                        this.Tables[t5].Rows[index].Cells[2].Range.Text = tax.AmmountPrefix;
                        this.Tables[t5].Rows[index].Cells[3].Range.Text = string.Format(num, "{0:#,0.00}", tax.Taxamount);
                    }
                }
            }
            catch (Exception) { }
        }

        /// <summary>
        /// establece los totales en 0, y elimina de las lineas correspondientes a Iva de las tablas de totales
        /// </summary>
        private void ResetTotals()
        {
            try
            {

                int startIndex = 3;
                int LastIndex = this.Tables[t5].Rows.Last.Previous.Index;
                int nRows = LastIndex - startIndex;

                if (nRows > 1)
                {

                    for (int i = 1; i < nRows; i++)
                    {
                        this.Tables[t5].Rows[4].Delete();
                    }
                }


            }
            catch (Exception) { }
        }

        /// <summary>
        /// actualiza la tabla de totales en los apartados de Importe total bruto, descuentos generales, IRPF y Total a pagar, 
        /// ya que los correspondientes al IVA se actualizan con las operaciones de los detalles
        /// </summary>
        private void updateResultsTable()
        {
            try
            {
                ResetTotals();
                this.Tables[t5].Rows[2].Cells[3].Range.Text = string.Format(num, "{0:#,0.00}", calculos.totalGrossAmount);
                this.Tables[t5].Rows[3].Cells[3].Range.Text = string.Format(num, "{0:#,0.00}", calculos.totalGeneralDiscount);
                setTaxesOutputs();
                this.Tables[t5].Rows.Last.Previous.Cells[3].Range.Text = string.Format(num, "{0:#,0.00}", calculos.totalTaxesWithHeld);
                this.Tables[t5].Rows.Last.Cells[3].Range.Text = string.Format(num, "{0:#,0.00}", calculos.totalAmount);
            }
            catch (Exception) { }
        }

        private void setDetailLineData(bool newDetail, int i, string fecha, string concepto, double ud, double precio, double descuento, double iva, double irpf, double baseimp, double total)
        {
            if (newDetail)
            {
                this.Tables[t2].Rows[i].Cells[1].Range.Text = fecha;
                this.Tables[t2].Rows[i].Cells[2].Range.Text = concepto;
                this.Tables[t2].Rows[i].Cells[6].Range.Text = string.Format(num, "{0:#,0.00}", iva);
            }
            this.Tables[t2].Rows[i].Cells[3].Range.Text = string.Format(num, "{0:#,0.00}", ud);
            this.Tables[t2].Rows[i].Cells[4].Range.Text = string.Format(num, "{0:#,0.00}", precio);
            this.Tables[t2].Rows[i].Cells[5].Range.Text = string.Format(num, "{0:#,0.00}", descuento);
            this.Tables[t2].Rows[i].Cells[7].Range.Text = string.Format(num, "{0:#,0.00}", irpf);
            this.Tables[t2].Rows[i].Cells[8].Range.Text = string.Format(num, "{0:#,0.00}", baseimp);
            this.Tables[t2].Rows[i].Cells[9].Range.Text = string.Format(num, "{0:#,0.00}", total);
        }

        /// <summary>
        /// método que se encarga de identificar los indices de las tablas.
        /// <para>
        /// Cada una de las tablas tiene un número en el encabezado, que permite identificarlas sin importar el orden en que aparezcan,
        /// se llama al inicio de cada operacion de cálculos,para aseguraserse de que las las variables de los indices esten actualizadas
        /// en caso de que una tabla haya sido eliminada
        /// 
        /// <example>
        /// se toma el texto del encabezado de la tabla, 
        /// 
        /// <code>string table = this.Tables[i].Rows[1].Cells[1].Range.Text.Trim(x).Trim();</code>
        /// 
        /// con base en el valor de "table", se asigna el indice a cada una de las variables para indices, t1,t2,t3,t4.t5,t6
        /// </example>
        /// </para>
        /// 
        /// </summary>
        private void enumerateTables()
        {
            try
            {
                for (int i = 2; i <= this.Tables.Count; i++)
                {

                    string table = this.Tables[i].Rows[1].Cells[1].Range.Text.Trim(x).Trim();

                    switch (table)
                    {

                        case "2":
                            t2 = i; break;
                        case "3":
                            t3 = i; break;
                        case "6":
                            t4 = i; break;
                        case "4":
                            t5 = i; break;
                        case "1":
                            t6 = i; break;
                        //case "7":
                        //    t7 = i; break;

                    }
                }
            }
            catch (Exception) { }


        }

        /// <summary>
        /// devuelve el valor de un enumerado de tipo xmlEnum
        /// </summary>
        /// <param name="e"> enumerado del cual se desea recuperar el valor</param>
        /// <returns>el valor correspondiente al enumerado, 
        /// <para>
        /// 
        /// <example>
        /// se tiene el siguiente enumerado:
        /// 
        /// <code>
        ///  [XmlTypeAttribute]
        /// public enum elementos
        /// {
        /// ["elemento 1"]
        /// item1,
        /// ["eliminado 2"]
        /// item2
        /// }
        /// </code>
        /// 
        /// la llamada:
        /// <code>
        /// ConvertToString(elementos.item1);
        /// </code>
        /// devulve: 
        /// 
        /// "elemento 1"
        /// </example>
        /// </para>
        /// 
        /// 
        /// </returns>
        private string ConvertToString(Enum e)
        {
            // Get the Type of the enum
            Type t = e.GetType();

            // Get the FieldInfo for the member field with the enums name
            FieldInfo info = t.GetField(e.ToString("G"));

            // Check to see if the XmlEnumAttribute is defined on this field
            if (!info.IsDefined(typeof(XmlEnumAttribute), false))
            {
                // If no XmlEnumAttribute then return the string version of the enum.
                return e.ToString("G");
            }

            // Get the XmlEnumAttribute
            object[] o = info.GetCustomAttributes(typeof(XmlEnumAttribute), false);
            XmlEnumAttribute att = (XmlEnumAttribute)o[0];
            return att.Name;
        }

        /// <summary>
        /// carga las entradas de el combobox indicado, con un array de strings
        /// </summary>
        /// <param name="cbx">combobox que se va a cargar</param>
        /// <param name="data">array de string con el que se va a cargar el combobox </param>
        private void LoadComboBox(ComboBoxContentControl cbx, string[] data)
        {
            try
            {
                int index = 0;
                for (int i = 0; i < data.Length; i++)
                {
                    cbx.DropDownListEntries.Add(data[i], data[i + 1], index);
                    i++; index++;
                }

            }
            catch (Exception)
            {

            }

        }

        /// <summary>
        /// actualiza los valores de los combobox que contienen el número de línea, en las tablas de detalle y descuento, 
        /// recorre el numero de itemes de las tablas y agrega el numero de elemeto a los combobox, permitiendo saber cual fila se desea eliminar o modificar
        /// </summary>
        /// <param name="cbx">combobox a actualizar</param>
        /// <param name="tableIndex">indice de la tabla al que corresponde el combobox</param>
        private void cargarN_Fila(ComboBox cbx, int tableIndex)
        {

            try
            {
                if (this.Tables[tableIndex].Rows.Count > 3)
                {
                    System.Data.DataTable table = new System.Data.DataTable();
                    DataColumn cName = new DataColumn("Name");
                    DataColumn cValue = new DataColumn("Value");
                    table.Columns.Add(cName);
                    table.Columns.Add(cValue);

                    for (int i = 3; i < this.Tables[tableIndex].Rows.Count; i++)
                    {
                        table.Rows.Add((i - 2).ToString(), i.ToString());

                    }

                    cbx.DataSource = table;
                    cbx.DisplayMember = "Name";
                    cbx.ValueMember = "Value";
                }
            }
            catch (Exception) { }

        }

        /// <summary>
        /// método que permite bloquear el documento para que no pueda ser editado cuando sea una factura recibida o se haya emitido
        /// agrupa las tablas, y bloquea los contentControls
        /// </summary>
        private void protectIssuedDocument()
        {
            try
            {
                string status = txtStatus.Text.Trim();
                int tableIndex = 1;
                if (!string.IsNullOrEmpty(status))
                {
                    if (status.ToUpper().Equals("ISSUED") || status.ToUpper().Equals("RECEIVED"))
                    {

                        try
                        {

                            foreach (Microsoft.Office.Interop.Word.ContentControl control in this.Application.ActiveDocument.ContentControls)
                            {
                                control.LockContentControl = true;
                                control.LockContents = true;

                            }
                        }
                        catch (Exception) { }

                        try
                        {

                            foreach (Word.Table table in this.Application.ActiveDocument.Tables)
                            {
                                Word.Range range = table.Range;
                                range.Select();
                                this.Controls.AddGroupContentControl("groupControl" + tableIndex.ToString());
                                tableIndex++;
                            }
                        }
                        catch (Exception) { }

                        try
                        {
                            this.btnAddDetails2.Dispose();
                            this.btnAddDiscount2.Dispose();
                            this.btnDeleteDetails2.Dispose();
                            this.btnDeleteDiscount2.Dispose();
                            this.btnModifyDetails2.Dispose();
                            this.btnModifyDiscount2.Dispose();
                            this.cbxnDetails.Dispose();
                            this.cbxnDiscount.Dispose();

                            this.lbnDetails.Text = "";
                            this.lbnDiscounts.Text = "";


                        }
                        catch (Exception) { }


                    }
                    this.dtpIssueDate.Range.Select();
                }

            }
            catch (Exception) { }

        }

        private void loadCorrectiveReason(string path, string tag)
        {
            try
            {
                string datos = ReadFile(path);
                string[] data;
                Microsoft.Office.Interop.Word.ContentControl ctr = getControlByTag(tag);
                if (ctr != null)
                {
                    if (!string.IsNullOrEmpty(datos))
                    {
                        data = datos.Replace("\r\n", "\t").Trim().Split('\t');
                        ctr.DropdownListEntries.Clear();

                        try
                        {
                            int index = 0;
                            for (int i = 0; i < data.Length; i++)
                            {
                                ctr.DropdownListEntries.Add(data[i], data[i + 1], index);
                                i++; index++;
                            }

                        }
                        catch (Exception) { }
                    }
                }


            }
            catch (Exception bh)
            {
            }
        }

        /// <summary>
        /// Método que busca un control por su tag y lo devuelve
        /// </summary>
        /// <param name="tag">Parámetro con el tag del control a buscar</param>
        /// <returns>El ContentControl con el tag especificado por parámetro o null si no se encuentra</returns>
        private Microsoft.Office.Interop.Word.ContentControl getControlByTag(String tag)
        {
            Microsoft.Office.Interop.Word.ContentControl cc = null;
            try
            {
                foreach (Microsoft.Office.Interop.Word.ContentControl item in this.ContentControls)
                {
                    if (!string.IsNullOrEmpty(item.Tag))
                    {
                        if (item.Tag.ToLower().Equals(tag.ToLower()))
                        {
                            cc = item; break;
                        }

                    }
                }
            }
            catch (Exception) { }
            return cc;
        }

        /// <summary>
        /// Método que devuelve una cádena con los datos almacenados en el archivo especificado en 
        /// el path que recibe por parámetro.
        /// </summary>
        /// <param name="path">Ruta del archivo que vamos a leer</param>
        /// <returns>Un string con los datos en forma de cadena</returns>
        private string ReadFile(string path)
        {
            try
            {
                using (StreamReader sr = new StreamReader(path, Encoding.Default))
                {
                    return sr.ReadToEnd();
                }
            }
            catch (Exception) { return ""; }
        }



        /// <summary>
        ///Busca el ContentControl con el nombre especificado y devuelve el texto digitado
        /// </summary>
        /// <param name="tag">enumerado de tipo ControlList.tag que representa el nombre del contentControl</param>
        /// <returns>el Valor del contentControl con nombre = tag</returns>
        public string getControlValueByTag(string tag)
        {
            string value = null;
            if (string.IsNullOrEmpty(tag))
                return value;
            foreach (Microsoft.Office.Interop.Word.ContentControl item in this.ContentControls)
            {
                if (!string.IsNullOrEmpty(item.Tag))
                {
                    if (item.Tag.Equals(tag))
                    {
                        if (string.IsNullOrEmpty(item.Range.Text))
                            return value;
                        value = item.Range.Text.Trim();
                        break;
                    }
                }
            }

            return value;


        }

        /// <summary>
        /// Busca el texto seleccionado en un DropDownListContentControl y devuelve el valor correspondiente
        /// </summary>
        /// <param name="tag">Representa el nombre del DropDownListContentControl del que se desea obtener el valor</param>
        /// <param name="selectedItem">Texto seleccionado en el DropDownListContentControl</param>
        /// <returns>el valor correspondiente al texto seleccionado en el DropDownListContentControl</returns>
        private string controlValue(string tag, string selectedItem)
        {
            string value = "";

            if (string.IsNullOrEmpty(tag))
                return value;

            /*buscamos el combobox indicado*/
            foreach (Microsoft.Office.Interop.Word.ContentControl item in this.ContentControls)
            {
                if (!string.IsNullOrEmpty(item.Tag))
                {
                    if (item.Tag.Equals(tag))
                    {
                        /*si lo encontramos buscamos el valor correspondiente al texto seleccionado*/
                        foreach (ContentControlListEntry entry in item.DropdownListEntries)
                        {
                            if (!string.IsNullOrEmpty(item.Tag))
                            {
                                if (entry.Text.ToLower().Equals(selectedItem.ToLower()))
                                {
                                    value = entry.Value; break;
                                }
                            }

                        } break;
                    }
                }
            }
            return value;
        }






        #endregion

        #region Validating Methods

        private void txtUd_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                txtUd.Text = ff.txtUd_Validating(txtUd.Text.Trim());
            }
            catch (Exception ex)
            {
                MessageBox.Show(Loader.LoadLabel(messagePath, ex.Message), Loader.LoadLabel(messagePath, "captionDetails"), MessageBoxButtons.OK, MessageBoxIcon.Stop, MessageBoxDefaultButton.Button1);
                txtUd.Range.Select();

            }
        }

        /// <summary>
        /// verifica el valor introducido para el descuento de linea, e indica al usuario si el valor es negativo
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtDiscount_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                txtDiscount.Text = ff.txtDiscount_Validating(txtDiscount.Text.Trim());
            }
            catch (Exception ex)
            {
                MessageBox.Show(Loader.LoadLabel(messagePath, ex.Message), Loader.LoadLabel(messagePath, "captionDetails"), MessageBoxButtons.OK, MessageBoxIcon.Stop, MessageBoxDefaultButton.Button1);
                txtDiscount.Range.Select();
            }

        }

        /// <summary>
        /// verifica el valor introducido para el descuento general, e indica al usuario si el valor es negativo
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtDiscountRate_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {

                txtDiscountRate.Text = ff.txtDiscount_Validating(txtDiscountRate.Text.Trim());
            }
            catch (Exception ex)
            {
                MessageBox.Show(Loader.LoadLabel(messagePath, ex.Message), Loader.LoadLabel(messagePath, "captionDetails"), MessageBoxButtons.OK, MessageBoxIcon.Stop, MessageBoxDefaultButton.Button1);
                txtDiscountRate.Range.Select();
            }

        }

        private void txtPrice_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                txtPrice.Text = ff.txtPrice_Validating(txtPrice.Text.Trim());
            }
            catch (Exception ex)
            {
                MessageBox.Show(Loader.LoadLabel(messagePath, ex.Message), Loader.LoadLabel(messagePath, "captionDetails"), MessageBoxButtons.OK, MessageBoxIcon.Stop, MessageBoxDefaultButton.Button1);
                txtPrice.Range.Select();
            }
        }


        private void txtExchangeRate_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                txtExchangeRate.Text = ff.txtExchangeRate(txtExchangeRate.Text.Trim());
            }
            catch (Exception ex)
            {
                MessageBox.Show(Loader.LoadLabel(messagePath, ex.Message), Loader.LoadLabel(messagePath, "captionDetails"), MessageBoxButtons.OK, MessageBoxIcon.Stop, MessageBoxDefaultButton.Button1);
                txtExchangeRate.Range.Select();
            }
        }


        private void cbxIVA_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                cbxIVA.Text = ff.cbxIVA_Validating(cbxIVA.Text.Trim());
            }
            catch (Exception ex)
            {
                MessageBox.Show(Loader.LoadLabel(messagePath, ex.Message), Loader.LoadLabel(messagePath, "captionDetails"), MessageBoxButtons.OK, MessageBoxIcon.Stop, MessageBoxDefaultButton.Button1);
                cbxIVA.Range.Select();
            }
        }

        private void txtIRPF_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                txtIRPF.Text = ff.txtIRPF_Validating(txtIRPF.Text.Trim());
            }
            catch (Exception ex)
            {
                MessageBox.Show(Loader.LoadLabel(messagePath, ex.Message), Loader.LoadLabel(messagePath, "captionDetails"), MessageBoxButtons.OK, MessageBoxIcon.Stop, MessageBoxDefaultButton.Button1);
                txtIRPF.Range.Select();
            }
        }

        private void cbxCountryEM_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                string country = controlValue("SP_CountryCode", cbxCountryEM.Range.Text.Trim());
                string cif = txtCifEM.Range.Text.Trim();
                this.txtCifEM.Text = validarCif(false, country, cif, 1);
            }
            catch (Exception) { }

        }

        private void cbxCountryTH_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                string country = controlValue("TH_CountryCode", cbxCountryTH.Range.Text.Trim());
                string cif = txtCifTH.Range.Text.Trim();
                this.txtCifTH.Text = validarCif(false, country, cif, 3);
            }
            catch (Exception) { }
        }

        private void cbxCountryBP_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {

                string country = controlValue("BP_CountryCode", cbxCountryBP.Range.Text.Trim());
                string cif = txtCifBP.Range.Text.Trim();
                this.txtCifBP.Text = validarCif(false, country, cif, 2);
            }
            catch (Exception) { }
        }

        private void txtCifEM_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                string country = controlValue("SP_CountryCode", cbxCountryEM.Range.Text.Trim());
                string cif = txtCifEM.Range.Text.Trim();
                this.txtCifEM.Text = validarCif(true, country, cif, 1);
            }
            catch (Exception) { }
        }

        private void txtCifBP_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                string country = controlValue("BP_CountryCode", cbxCountryBP.Range.Text.Trim());
                string cif = txtCifBP.Range.Text.Trim();
                this.txtCifBP.Text = validarCif(true, country, cif, 2);
            }
            catch (Exception) { }
        }

        private void txtCifTH_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                string country = controlValue("TH_CountryCode", cbxCountryTH.Range.Text.Trim());
                string cif = txtCifTH.Range.Text.Trim();
                this.txtCifTH.Text = validarCif(true, country, cif, 3);
            }
            catch (Exception) { }
        }

        /// <summary>
        /// realiza la llamada al metodo de validacion de cif para la parte correspondiente
        /// </summary>
        /// <param name="cifvalidation"></param>
        /// <param name="country"></param>
        /// <param name="cif"></param>
        /// <param name="party">indica a cual de las partes pertenece el cif, 1 = emisor, 2 = receptor, 3 = tercero</param>
        private string validarCif(bool cifvalidation, string country, string cif, int party)
        {
            try
            {
                if (String.IsNullOrEmpty(cif))
                {
                    return "";
                }
                return Validations.validarCif(cifvalidation, country, cif);
            }
            catch (Exception ex)
            {
                string label = ex.Message;

                if (label.Equals("countrynotinlist"))
                {
                    switch (party)
                    {
                        case 1: cbxCountryEM.Range.Select(); break;
                        case 2: cbxCountryBP.Range.Select(); break;
                        case 3: cbxCountryTH.Range.Select(); break;
                    }

                }
                else
                {
                    switch (party)
                    {
                        case 1:
                            label = "ErrorInvalidCIFSP";
                            txtCifEM.Range.Select(); break;
                        case 2:
                            label = "ErrorInvalidCIFBP";
                            txtCifBP.Range.Select(); break;
                        case 3:
                            label = "ErrorInvalidCIFTH";
                            txtCifTH.Range.Select(); break;
                    }
                }

                MessageBox.Show(Loader.LoadLabel(messagePath, label), "Factura Electrónica", MessageBoxButtons.OK, MessageBoxIcon.Stop, MessageBoxDefaultButton.Button1);

            }
            return null;
        }

        #endregion

        #region Enums

        /// <summary>
        /// enumerado de codigos de país, incluidos en el esquema de facturae, se utilizan para cargar los combos de paises
        /// </summary>
        private enum CurrencyCodeType
        {

            /// <comentarios/>
            AFN,

            /// <comentarios/>
            ALL,

            /// <comentarios/>
            AMD,

            /// <comentarios/>
            ANG,

            /// <comentarios/>
            AOA,

            /// <comentarios/>
            ARS,

            /// <comentarios/>
            AUD,

            /// <comentarios/>
            AWG,

            /// <comentarios/>
            AZN,

            /// <comentarios/>
            BAD,

            /// <comentarios/>
            BBD,

            /// <comentarios/>
            BDT,

            /// <comentarios/>
            BGN,

            /// <comentarios/>
            BHD,

            /// <comentarios/>
            BIF,

            /// <comentarios/>
            BMD,

            /// <comentarios/>
            BND,

            /// <comentarios/>
            BOB,

            /// <comentarios/>
            BRL,

            /// <comentarios/>
            BRR,

            /// <comentarios/>
            BSD,

            /// <comentarios/>
            BWP,

            /// <comentarios/>
            BYR,

            /// <comentarios/>
            BZD,

            /// <comentarios/>
            CAD,

            /// <comentarios/>
            CDF,

            /// <comentarios/>
            CDP,

            /// <comentarios/>
            CHF,

            /// <comentarios/>
            CLP,

            /// <comentarios/>
            CNY,

            /// <comentarios/>
            COP,

            /// <comentarios/>
            CRC,

            /// <comentarios/>
            CUP,

            /// <comentarios/>
            CVE,

            /// <comentarios/>
            CZK,

            /// <comentarios/>
            DJF,

            /// <comentarios/>
            DKK,

            /// <comentarios/>
            DOP,

            /// <comentarios/>
            DRP,

            /// <comentarios/>
            DZD,

            /// <comentarios/>
            EEK,

            /// <comentarios/>
            EGP,

            /// <comentarios/>
            ESP,

            /// <comentarios/>
            ETB,

            /// <comentarios/>
            EUR,

            /// <comentarios/>
            FJD,

            /// <comentarios/>
            FKP,

            /// <comentarios/>
            GBP,

            /// <comentarios/>
            GEK,

            /// <comentarios/>
            GHC,

            /// <comentarios/>
            GIP,

            /// <comentarios/>
            GMD,

            /// <comentarios/>
            GNF,

            /// <comentarios/>
            GTQ,

            /// <comentarios/>
            GWP,

            /// <comentarios/>
            GYD,

            /// <comentarios/>
            HKD,

            /// <comentarios/>
            HNL,

            /// <comentarios/>
            HRK,

            /// <comentarios/>
            HTG,

            /// <comentarios/>
            HUF,

            /// <comentarios/>
            IDR,

            /// <comentarios/>
            ILS,

            /// <comentarios/>
            INR,

            /// <comentarios/>
            IQD,

            /// <comentarios/>
            IRR,

            /// <comentarios/>
            ISK,

            /// <comentarios/>
            JMD,

            /// <comentarios/>
            JOD,

            /// <comentarios/>
            JPY,

            /// <comentarios/>
            KES,

            /// <comentarios/>
            KGS,

            /// <comentarios/>
            KHR,

            /// <comentarios/>
            KMF,

            /// <comentarios/>
            KPW,

            /// <comentarios/>
            KRW,

            /// <comentarios/>
            KWD,

            /// <comentarios/>
            KYD,

            /// <comentarios/>
            KZT,

            /// <comentarios/>
            LAK,

            /// <comentarios/>
            LBP,

            /// <comentarios/>
            LKR,

            /// <comentarios/>
            LRD,

            /// <comentarios/>
            LSL,

            /// <comentarios/>
            LTL,

            /// <comentarios/>
            LVL,

            /// <comentarios/>
            LYD,

            /// <comentarios/>
            MAD,

            /// <comentarios/>
            MDL,

            /// <comentarios/>
            MGF,

            /// <comentarios/>
            MNC,

            /// <comentarios/>
            MNT,

            /// <comentarios/>
            MOP,

            /// <comentarios/>
            MRO,

            /// <comentarios/>
            MUR,

            /// <comentarios/>
            MVR,

            /// <comentarios/>
            MWK,

            /// <comentarios/>
            MXN,

            /// <comentarios/>
            MYR,

            /// <comentarios/>
            MZM,

            /// <comentarios/>
            NGN,

            /// <comentarios/>
            NIC,

            /// <comentarios/>
            NIO,

            /// <comentarios/>
            NIS,

            /// <comentarios/>
            NOK,

            /// <comentarios/>
            NPR,

            /// <comentarios/>
            NZD,

            /// <comentarios/>
            OMR,

            /// <comentarios/>
            PAB,

            /// <comentarios/>
            PEI,

            /// <comentarios/>
            PEN,

            /// <comentarios/>
            PES,

            /// <comentarios/>
            PGK,

            /// <comentarios/>
            PHP,

            /// <comentarios/>
            PKR,

            /// <comentarios/>
            PLN,

            /// <comentarios/>
            PYG,

            /// <comentarios/>
            QAR,

            /// <comentarios/>
            RMB,

            /// <comentarios/>
            RON,

            /// <comentarios/>
            RUB,

            /// <comentarios/>
            RWF,

            /// <comentarios/>
            SAR,

            /// <comentarios/>
            SBD,

            /// <comentarios/>
            SCR,

            /// <comentarios/>
            SDP,

            /// <comentarios/>
            SEK,

            /// <comentarios/>
            SGD,

            /// <comentarios/>
            SHP,

            /// <comentarios/>
            SKK,

            /// <comentarios/>
            SLL,

            /// <comentarios/>
            SOL,

            /// <comentarios/>
            SOS,

            /// <comentarios/>
            SRD,

            /// <comentarios/>
            STD,

            /// <comentarios/>
            SVC,

            /// <comentarios/>
            SYP,

            /// <comentarios/>
            SZL,

            /// <comentarios/>
            THB,

            /// <comentarios/>
            TJS,

            /// <comentarios/>
            TMM,

            /// <comentarios/>
            TND,

            /// <comentarios/>
            TOP,

            /// <comentarios/>
            TPE,

            /// <comentarios/>
            TRY,

            /// <comentarios/>
            TTD,

            /// <comentarios/>
            TWD,

            /// <comentarios/>
            TZS,

            /// <comentarios/>
            UAH,

            /// <comentarios/>
            UGS,

            /// <comentarios/>
            USD,

            /// <comentarios/>
            UYP,

            /// <comentarios/>
            UYU,

            /// <comentarios/>
            VEF,

            /// <comentarios/>
            VND,

            /// <comentarios/>
            VUV,

            /// <comentarios/>
            WST,

            /// <comentarios/>
            XAF,

            /// <comentarios/>
            XCD,

            /// <comentarios/>
            XOF,

            /// <comentarios/>
            YER,

            /// <comentarios/>
            ZAR,

            /// <comentarios/>
            ZMK,

            /// <comentarios/>
            ZWD,
        }

        #endregion

        #region VSTO Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.btnAddDetails2.Click += new System.EventHandler(this.btnAddDetails_Click);
            this.btnDeleteDetails2.Click += new System.EventHandler(this.btnDeleteDetails_Click);
            this.btnModifyDetails2.Click += new System.EventHandler(this.btnModifyDetails_Click);
            this.btnAddDiscount2.Click += new System.EventHandler(this.btnAddDiscount_Click);
            this.btnDeleteDiscount2.Click += new System.EventHandler(this.btnDeleteDiscount_Click);
            this.btnModifyDiscount2.Click += new System.EventHandler(this.btnModifyDiscount_Click);
            this.txtCifEM.Validating += new System.ComponentModel.CancelEventHandler(this.txtCifEM_Validating);
            this.txtCifBP.Validating += new System.ComponentModel.CancelEventHandler(this.txtCifBP_Validating);
            this.cbxCountryEM.Validating += new System.ComponentModel.CancelEventHandler(this.cbxCountryEM_Validating);
            this.cbxCountryBP.Validating += new System.ComponentModel.CancelEventHandler(this.cbxCountryBP_Validating);
            this.txtUd.Validating += new System.ComponentModel.CancelEventHandler(this.txtUd_Validating);
            this.txtPrice.Validating += new System.ComponentModel.CancelEventHandler(this.txtPrice_Validating);
            this.txtDiscount.Validating += new System.ComponentModel.CancelEventHandler(this.txtDiscount_Validating);
            this.cbxIVA.Validating += new System.ComponentModel.CancelEventHandler(this.cbxIVA_Validating);
            this.txtIRPF.Validating += new System.ComponentModel.CancelEventHandler(this.txtIRPF_Validating);
            this.txtDiscountRate.Validating += new System.ComponentModel.CancelEventHandler(this.txtDiscountRate_Validating);
            this.txtExchangeRate.Validating += new System.ComponentModel.CancelEventHandler(this.txtExchangeRate_Validating);
            this.Startup += new System.EventHandler(this.ThisDocument_Startup);
            this.Shutdown += new System.EventHandler(this.ThisDocument_Shutdown);

        }

        #endregion




    }
}
